import {defineStore, storeToRefs} from "pinia";
import {getInterfaceCatTreeApi, postInterfaceApi, RunInterfaceTest} from "@/api/modules/interface/interface.js";
import {useProjectStore} from "@/stores/modules/project/project.js";
import {ElMessage} from "element-plus";
import {useWebSocket} from '@vueuse/core'
import {getGuidApi} from "@/api/modules/system/common.js";

const projectStore = useProjectStore()

const {currentProject, currentProjectId} = storeToRefs(projectStore)

export const useInterfaceStore = defineStore({
    id: "chestnut-interface",
    state: () => ({
        // 接口分类的树
        interfaceCatTree: [],
        // 当前选中的分类名
        selectedInterfaceCatName: "",
        // 当前选中的分类ID
        selectedInterfaceCatId: "",
        // 展示接口列表，还是编辑页
        showInterfaceList: true,
        // 当前选中的TAB name
        currentActiveTab: "interfaceList",
        // 存放当前选中的接口的TABS(已选中A，B，C；三个接口的tab数据放入interfaceTabsList中)
        // {id:"12345", method:"GET", interfaceName:"inter1"}
        // interfaceTabsList: [],
        // 存放当前选中的接口的列表(tab中接口列表的数据)
        interfaceList: [],
        // 存放当前选中的接口的列表(已选中A，B，C；三个接口的数据放入interfaceSourceList中)
        interfaceSourceList: [],
        // 当前正在进行操作的接口,(点击接口的tab时，选中的接口，即当前正在编辑的接口),后续场景定义中，可直接传该类型的数据
        // currentInterface: {}
    }),
    actions: {
        // 获取接口模块的树
        async getInterfaceCatTree() {
            console.log(currentProjectId.value)
            await getInterfaceCatTreeApi({projectId: currentProjectId.value}).then(res => {
                this.interfaceCatTree = res.data
            })
        },
        // 添加一个接口到接口资源中
        addInitInterfaceSource(catId = undefined) {
            // 在分类树中，直接点击新增接接口时，需要传入catId
            this.interfaceSourceList.push({
                id: this.currentActiveTab,
                path: "https://www.baidu.com/",
                method: "GET",
                name: "undefined",
                parameters: {
                    Params: [{key: "", value: "", description: "", enable: true}],
                    Headers: [{key: "", value: "", description: "", enable: true}]
                },
                requestBody: {
                    type: "application/json",
                    // json,xml,plain,html
                    text: {
                        string: ""
                    },
                    // form-data,x-www-form-urlencoded
                    form_data: [{key: "", value: "", description: "", enable: true}],
                    // octet-stream
                    octet_stream: []
                },
                preProcessors: {
                    string: ""
                },
                postProcessors: {
                    string: ""
                },
                advancedSettings: {
                    env: ""
                },
                cat: catId ? catId : this.selectedInterfaceCatId,
                project: currentProjectId.value,
                response_id:"",
                response_time:0,
                response_status:"",
                response_size:"",
                response_headers:"",
                response_body:"",
                console_out:""
            })
        },

        // 移除接口
        async removeInterface(tabPath, isCurrent = true) {
            if (isCurrent) {
                this.interfaceList.forEach((item, index) => {
                    if (item.path !== tabPath) return;
                    const nextTab = this.interfaceList[index + 1] || this.interfaceList[index - 1];
                    if (!nextTab) return;
                    router.push(nextTab.path);
                });
            }
        },

        // 关闭两边的接口TABs
        async closeInterfaceOnSide(path, type) {
            const currentIndex = this.interfaceList.findIndex(item => item.path === path);
            if (currentIndex !== -1) {
                const range = type === "left" ? [0, currentIndex] : [currentIndex + 1, this.tabsMenuList.length];
                this.interfaceList = this.interfaceList.filter((item, index) => {
                    return index < range[0] || index >= range[1] || !item.close;
                });
            }
        },
        saveRequestReturnResult(ws, event) {
            // event.data 返回的数据
            let returnResult = JSON.parse(event.data)
            if (returnResult.type === "heartbeat") {
                console.log("heartbeat")
                // console.log(event.data)
            } else if (returnResult.type === "RequestReturnResult") {
                console.log(event.data)
                ws.close()

            }
        },
        async sendRequest(currentInterface) {
            RunInterfaceTest({
                id: currentInterface["id"],
                path: currentInterface["path"],
                method: currentInterface["method"],
                name: currentInterface["name"],
                parameters: currentInterface["parameters"],
                requestBody: currentInterface["requestBody"],
                preProcessors: currentInterface["preProcessors"],
                postProcessors: currentInterface["postProcessors"],
                advancedSettings: currentInterface["advancedSettings"],
                project: currentInterface["project"]
            }).then(res=>{

            })
        },

        async saveRequest(currentInterface) {
            postInterfaceApi(currentInterface).then(res => {
                ElMessage.success("成功")
            })
        }

    }

})
